from django.shortcuts import render, redirect

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from meiduo_mall.settings import dev
from oauth.exceptions import QQAPIError, SINAAPIError
from oauth.models import OAuthQQUser, OAuthSinaUser
from oauth.serializers import OAuthQQUserSerializer, OAuthSINAUserSerializer
from oauth.utils import OAuthQQ, OAuthSINA

#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
from verifications.views import logger


class QQAuthURLView(APIView):
    """
    QQ登录的url地址:
    """
    def get(self, request):
        next = request.query_params.get('next', '/')
        # 获取qq登录url地址
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_login_url()

        return Response({'login_url': login_url})


# 第二步    　在QQ将用户重定向到此网页的时候，重定向的网址会携带QQ提供的code参数，
#           用于获取用户信息使用，我们需要将这个code参数发送给后端，
#           在后端中使用code参数向QQ请求用户的身份信息，并查询与该QQ用户绑定的用户。
# 接口　GET /oauth/qq/user/?code=xxx

# 第三步　　　绑定用户post
# 接口　POST /oauth/qq/user/
class QQAuthUserView(CreateAPIView):
    """
       QQ登录的用户
       """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        # 1. 获取QQ返回的code
        code = request.query_params.get('code')

        try:
            # 2. 根据code获取access_token
            oauth = OAuthQQ()
            access_token = oauth.get_access_token(code)
            # 3. 根据access_token获取授权QQ用户的openid
            openid = oauth.get_openid(access_token)
        except QQAPIError as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4. 根据`openid`查询tb_oatu_qq表，判断是否已经绑定账号
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 4.2 如果未绑定，返回token
            token = oauth.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            # 4.1 如果已经绑定，生成JWT token信息
            # 补充生成记录登录状态的token
            user = oauth_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response


class SINAAuthURLView(APIView):
    """
    SINA登录的url地址:
    """
    def get(self, request):
        # 获取qq登录url地址
        next = request.query_params.get('next', '/')
        oauth = OAuthSINA(state=next)
        login_url = oauth.get_login_url()

        return Response({'login_url': login_url})


# 第三步　　　绑定用户post
# 接口　POST /oauth/sina/user/
class SINAAuthUserView(GenericAPIView):
    """
       sina登录的用户
       """
    serializer_class = OAuthSINAUserSerializer

    def get(self,request):
        # 1. 获取sina返回的code
        code =request.query_params.get('code')
        if code is None:
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            # 2. 根据code获取access_token
            oauth = OAuthSINA()
            access_token = oauth.get_access_token(code)
        except SINAAPIError as e:
            logger.error(e)
            return Response({'message': 'SINA服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 4. 根据`access_token`查询tb_oatu_qq表，判断是否已经绑定账号
        try:
            sina_user = OAuthSinaUser.objects.get(access_token = access_token)
        except OAuthSinaUser.DoesNotExist:
            # 4.2 如果未绑定，进行绑定
            response = {
                "access_token":access_token
            }
            return Response(response)
        else:
            # 4.1 如果已经绑定，生成JWT token信息
            # 补充生成记录登录状态的token
            user = sina_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            res_data = {
                'token': token,
                'user_id': user.id ,
                # 有问题20180228,绑定后的用户再次登录时
                'username': user.username
            }
            return Response(res_data)
    def post(self, request, *args, **kwargs):
        # {
        #     password: this.password,
        #     mobile: this.mobile,
        #     sms_code: this.sms_code,
        #     access_token: this.access_token
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception = True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)



